// src/utils/request.js
import axios from 'axios';
import { useAuthStore } from '@/stores/auth';
import router from '@/router';

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000
});

// 请求拦截器：自动添加Token
service.interceptors.request.use(config => {
  const authStore = useAuthStore();
  if (authStore.token) {
    config.headers.Authorization = `Bearer ${authStore.token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器：统一处理错误
service.interceptors.response.use(
  response => {
    return response.data;
  },
  async error => {
    const { response, config } = error;
    const authStore = useAuthStore();
    
    // 401处理：跳转登录页
    if (response?.status === 401) {
      await authStore.logout();
      router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
      return Promise.reject(new Error('请重新登录'));
    }
    
    // 403处理：提示权限不足
    if (response?.status === 403) {
      ElMessage.error(response.data?.message || '无权访问');
      return Promise.reject(error);
    }
    
    // 其他错误
    ElMessage.error(response?.data?.message || '服务异常');
    return Promise.reject(error);
  }
);

export default service;